import React, { useRef, useEffect, useState, useCallback } from 'react';
import { View } from '@tarojs/components';

export default function CustomRequestButton(props) {
  const { current } = useRef({});
  const [loading, setLoading] = useState(false);
  CustomRequestButton.loading = loading;

  useEffect(() => {
    CustomRequestButton.reset = function() {
      setLoading(false);
    };
  }, []);

  useEffect(() => {
    return () => {
      clearTimeout(current.timer);
    };
  }, [current.timer]);

  const checkFetch = useCallback(
    e => {
      e.stopPropagation();
      if (!loading && typeof props.onChecked === 'function') {
        if (props.onChecked()) {
          setLoading(true);
          current.timer = setTimeout(() => {
            current.timer && setLoading(false);
            current.timer = null;
          }, props.timeout || 10000);

          if (props.onSubmit) {
            props.onSubmit();
          }
        } else {
          setLoading(false);
        }
      }

      if (!loading && typeof props.onChecked === 'boolean') {
        if (props.onChecked) {
          setLoading(true);
          current.timer = setTimeout(() => {
            current.timer && setLoading(false);
            current.timer = null;
          }, props.timeout || 10000);

          if (props.onSubmit) {
            props.onSubmit();
          }
        }
      }
    },
    [props, loading, current.timer]
  );

  return (
    <View
      onClick={checkFetch}
      style={Object.assign({ pointerEvents: loading ? 'none' : 'auto' }, { ...props.style })}
    >
      {props.children}
    </View>
  );
}
